/*
 * LocAdapter.cpp
 *
 *  Created on: Nov 13, 2012
 *      Author: Scorpion
 */

#include "LocAdapter.h"
#include "CurlBuilder.h"
namespace centny {
LocFInfo::LocFInfo(LocAdapter *cb, LocFInfo *parent) :
		FInfo(cb, parent) {
}
LocFInfo::~LocFInfo() {
//	printf("free LocFInfo\n");
}
void LocFInfo::initByPath(const fs::path& p) {
	assert(fs::exists(p));
	if (parent) {
		this->name = p.filename().string();
		this->cwd = parent->cwd + F_SEQ + this->name;
	} else {
		this->name = "";
		this->cwd = "";
	}
	if (fs::is_directory(p)) {
		this->type = 'd';
		this->cwd += F_SEQ;
	} else {
		this->type = '-';
		assert(parent);
	}
	this->mtime = fs::last_write_time(p);
	boost::system::error_code ec;
	this->size = fs::file_size(p, ec);
	if (ec.value()) {
//		printf("read file size error:%s\n", ec.message().c_str());
		this->size = 0;
	}
}
void LocFInfo::fre() {
	delete this;
}
//
//
LocAdapter::LocAdapter(string rurl) {
	this->rurl = rurl;
	LocFInfo *lf = new LocFInfo(this, 0);
	lf->initByPath(fs::path(this->rurl));
	this->addToMap(lf);
}
LocAdapter::~LocAdapter() {
}
FInfo* LocAdapter::root() {
	this->fre();
	FInfo *fi = new LocFInfo(this, 0);
	fi->cwd = F_SEQ;
	fi->type = 'd';
	this->addToMap(fi);
	return fi;
}
vector<FInfo*> LocAdapter::subs(FInfo* parent) {
	assert(parent);
	vector<FInfo*> fsub;
	string rpath = this->rurl + parent->cwd;
	replaceAll(rpath, F_SEQ F_SEQ, F_SEQ, 0);
	fs::path ppath(rpath);
	assert(fs::exists(ppath));
	fs::directory_iterator it(ppath);
	fs::directory_iterator end;
	for (; it != end; it++) {
		LocFInfo *lf = new LocFInfo(this, (LocFInfo*) parent);
		lf->initByPath(it->path());
		fsub.push_back(lf);
		this->addToMap(lf);
	}
	return fsub;
}
FInfo* LocAdapter::mkdir(FInfo* fi, string name) {
	fs::path tp(fi->absUrl() + name);
	bool ced = fs::create_directories(tp);
	if (ced) {
		LocFInfo *lf = new LocFInfo(this, (LocFInfo*) fi);
		lf->initByPath(tp);
		this->addToMap(lf);
		return lf;
	} else {
		return 0;
	}
}
string LocAdapter::absUrl(FInfo* tg) {
	return this->rurl + F_SEQ + tg->cwd;
}
} /* namespace centny */
